import com.codezen.helper.Worker;

import flash.events.Event;

import mx.collections.ArrayCollection;
import mx.events.CollectionEvent;
import mx.utils.ObjectUtil;

import utils.anime.AniEpisode;
import utils.anime.AniEpisodesDB;
import utils.anime.AniSerial;
import utils.serials.Episode;
import utils.serials.EpisodesDB;
import utils.serials.Serial;

private var adb:AniEpisodesDB;
private var adbInit:Boolean;
private var aloadCounter:int = -1;
private var aloadAllCounter:int = -1;
private var aseasonCounter:int = -1;

private function initAniDatabase():void{
	adb = new AniEpisodesDB();
	// database
	adb.addEventListener(Event.INIT, function():void{
		trace('init');
		adbInit = true;
	});
	/*db.addEventListener(Database.CLOSED, function():void{
		//trace('closed');
		// open file
		/*var prefsFile:File = File.applicationStorageDirectory.resolvePath("default.db");
		// del file
		prefsFile.deleteFile();
	});*/
}

private function setAniEpisodeWatched(ep:AniEpisode):void{
	if(ep == null) return;
	if(ep.view == "true") return;
	ep.view = "true";
	adb.saveEpisode(ep);
	adb.addEventListener(Event.COMPLETE, onAniDbSave);
}

private function setAniEpisodeNotWatched(ep:AniEpisode):void{
	adb.delEpisode(ep);
	adb.addEventListener(Event.COMPLETE, onAniDbSave);
}

// set whole season as wached
private function setAniSeasonWatched():void{
	if(aseasonCounter == -1){
		aseasonCounter = episodesList.length - 1;
		setBusyCursor();
	}
	episodesList[aseasonCounter].view = "true";
	adb.saveEpisode(episodesList[aseasonCounter]);
	adb.addEventListener(Event.COMPLETE, onAniSeasonSave);
}

private function onAniSeasonSave(e:Event):void{
	adb.removeEventListener(Event.COMPLETE, onAniSeasonSave);
	aseasonCounter--;
	if(aseasonCounter < 0){
		removeBusyCursor();
		dbAniLoadEpisodes();	
		return;
	}
	setAniSeasonWatched();
}

// set whole season as wached
private function setAniSeasonNotWatched():void{
	if(aseasonCounter == -1){
		aseasonCounter = episodesList.length - 1;
		setBusyCursor();
	}
	adb.delEpisode(episodesList[aseasonCounter]);
	adb.addEventListener(Event.COMPLETE, onAniSeasonDel);
}

private function onAniSeasonDel(e:Event):void{
	adb.removeEventListener(Event.COMPLETE, onAniSeasonDel);
	aseasonCounter--;
	if(aseasonCounter < 0){
		removeBusyCursor();
		dbAniLoadEpisodes();	
		return;
	}
	setAniSeasonNotWatched();
}

// load series list from DB
private function dbAniLoadSeries():void{
	adb.addEventListener(Event.COMPLETE, onAniSeriesList);
	adb.getSeriesList();
}

private function onAniSeriesList(e:Event):void{
	// remove
	adb.removeEventListener(Event.COMPLETE, onAniSeriesList);
	// create new list
	if(iviewSeriesList == null) return;
		//iviewSeriesList = new ArrayCollection();
	// parse if something there
	if(adb.result != null && adb.result.data != null){
		var obj:Object;
		var s:AniSerial;
		for each(obj in adb.result.data){
			// create serial
			s = new AniSerial();
			// set data
			s.id = obj.serial_id;
			s.bimg = obj.serial_bimg;
			s.info = obj.serial_info;
			s.etitle = obj.serial_etitle;
			s.title = obj.serial_title;
			s.simg = obj.serial_simg;
			// add
			iviewSeriesList.addItem(s);
		}
		
		// create sort by names
		var sort:Sort = new Sort();
		sort.fields = [new SortField("title")];
		
		// sort
		iviewSeriesList.sort = sort;
		iviewSeriesList.refresh();
		
		// clean
		sort = null;
		obj = null;
		s = null;
	}
	
	// load saved
	dbLoadSaveEpisodes();
}

// load saved episodes from db
private function dbAniLoadSaveEpisodes():void{
	adb.addEventListener(Event.COMPLETE, onAniSavedEpisodeList);
	adb.getSavedEpisodesList();
}

private function onAniSavedEpisodeList(e:Event):void{
	// remove
	adb.removeEventListener(Event.COMPLETE, onAniSavedEpisodeList);
	// create new list
	//savedEpisodes = new ArrayCollection();
	
	// parse if something there
	if(adb.result != null && adb.result.data != null){
		var obj:Object;
		var ep:AniEpisode;
		for each(obj in adb.result.data){
			// create serial
			ep = new AniEpisode();
			// set data
			ep.serial_id = obj.serial_id;
			ep.serial_bimg = obj.serial_bimg;
			ep.serial_info = obj.serial_info;
			ep.serial_etitle = obj.serial_etitle;
			ep.serial_title = obj.serial_title;
			ep.serial_simg = obj.serial_simg;
			ep.id = obj.id;
			ep.aid = obj.aid;
			ep.image = obj.image;
			ep.num = obj.num;
			ep.season = obj.season;
			ep.title = obj.title;
			ep.tmark = obj.tmark;
			ep.video = obj.video;
			ep.view = obj.view;
			ep.sub1 = obj.sub1;
			ep.sub2 = obj.sub2;
			ep.snd1 = obj.snd1;
			ep.snd2 = obj.snd2;
			// add
			savedEpisodes.addItem(ep);
		}
		
		// create sort by names
		var sort:Sort = new Sort();
		sort.fields = [new SortField("title")];
		
		// sort
		savedEpisodes.sort = sort;
		savedEpisodes.refresh();
		
		// clean
		sort = null;
		obj = null;
		ep = null;
	}
}

// load new episodes from db
private function dbAniLoadNewEpisodes():void{
	if(aloadCounter == -1 && lastAniEpisodes != null && lastAniEpisodes.length > 0){
		aloadCounter = lastAniEpisodes.length - 1;
	}
	adb.addEventListener(Event.COMPLETE, onAniLoadComplete);
	adb.checkEpisode(lastAniEpisodes[aloadCounter]);
}

private function onAniLoadComplete(e:Event):void{
	// remove ev. list
	adb.removeEventListener(Event.COMPLETE, onAniLoadComplete);
	// check
	if(adb.result.data != null){
		lastAniEpisodes[aloadCounter].view = "true";
	}else{
		lastAniEpisodes[aloadCounter].view = null;
	}
	// continue
	aloadCounter--;
	if(aloadCounter < 0){
		lastAniEpisodes.refresh();
		// load watch series from db
		dbLoadSeries();
		// gc
		startGCCycle();
		return;
	} 
	dbAniLoadNewEpisodes();
}


// remove whole series from DB
private function dbRemoveAniSeries():void{
	adb.addEventListener(Event.COMPLETE, onAniDbSave);
	adb.removeSeries(currentAniSeries);
}

// load series episodes from DB
private function dbAniLoadEpisodes():void{
	if(aloadAllCounter == -1){
		aloadAllCounter = episodesList.length - 1;
	}
	adb.addEventListener(Event.COMPLETE, onAniEpisodesLoadComplete);
	adb.checkEpisode(episodesList[aloadAllCounter]);
}

private function onAniEpisodesLoadComplete(e:Event):void{
	// remove
	adb.removeEventListener(Event.COMPLETE, onAniEpisodesLoadComplete);
	// check
	if(adb.result.data != null){
		episodesList[aloadAllCounter].view = "true";
	}else{
		episodesList[aloadAllCounter].view = null;
	}
	// continue
	aloadAllCounter--;
	if(aloadAllCounter < 0){
		episodesList.refresh();
		// load watch series from db
		dbLoadSeries();
		// gc
		startGCCycle();
		return;
	} 
	dbAniLoadEpisodes();
}

private function onAniDbSave(e:Event):void{
	adb.removeEventListener(Event.COMPLETE, onAniDbSave);

	// work
	if(currentState == "Main" || (currentState == "Player" && oldState == "Main") ){
		dbAniLoadNewEpisodes();
	}
	if(currentState == "Series" || (currentState == "Player" && oldState == "Series") ){
		dbAniLoadEpisodes();
	}
	//trace( ObjectUtil.toString(db.result) );
}